package com.example.juc.interview;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * 手写LRU算法
 *
 * @author jl
 * @since 2021/11/7 11:24
 */
public class LRUCache<K, V> implements Iterable<K> {

    int MAX = 3;

    LinkedHashMap<K, V> cache = new LinkedHashMap<>();

    public void cache(K key, V value) {
        if (cache.containsKey(key)) {
            cache.remove(key);
        } else if (cache.size() >= MAX) {
            Iterator<K> it = cache.keySet().iterator();
            K first = it.next();
            cache.remove(first);
        }
        cache.put(key, value);
    }

    @Override
    public Iterator<K> iterator() {
        return new Iterator<K>() {
            Iterator<Map.Entry<K, V>> it = cache.entrySet().iterator();

            @Override
            public boolean hasNext() {
                return it.hasNext();
            }

            @Override
            public K next() {
                return it.next().getKey();
            }
        };
    }

    public static void main(String[] args) {
        LRUCache<String, Integer> lru = new LRUCache<>();
        lru.cache("A", 1);
        lru.cache("B", 2);
        lru.cache("C", 3);

        lru.cache("D", 4);
        lru.cache("C", 5);
        System.out.println("leave <-" + StreamSupport.stream(lru.spliterator(), false).map(String::toString).collect(Collectors.joining("<-")));
    }
}
